package com.zxf.basic.expand

import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

fun Any?.isNull() = this == null

/**
 * 切换主线程
 */
fun runOnMainThread(block: () -> Unit) {
    Observable.empty<Any>()
        .observeOn(AndroidSchedulers.mainThread())
        .doOnComplete(block)
        .subscribe()
}

/**
 * 切换主线程
 * @param delay 延迟
 * @param timeUnit 时间单位
 */
fun runOnMainThread(delay: Long, timeUnit: TimeUnit = TimeUnit.MILLISECONDS, block: () -> Unit) {
    Observable.empty<Any>()
        .delay(delay, timeUnit)
        .observeOn(AndroidSchedulers.mainThread())
        .doOnComplete(block)
        .subscribe()
}



/**
 * 切换子线程
 */
fun runOnSubThread(block: () -> Unit) {
    Observable.empty<Any>()
        .observeOn(Schedulers.io())
        .doOnComplete(block)
        .subscribe()
}

/**
 * 切换子线程
 * @param delay 延迟
 * @param timeUnit 时间单位
 */
fun runOnSubThread(delay: Long, timeUnit: TimeUnit = TimeUnit.MILLISECONDS, block: () -> Unit) {
    Observable.empty<Any>()
        .delay(delay, timeUnit)
        .observeOn(Schedulers.io())
        .doOnComplete(block)
        .subscribe()
}

/**
 * 强制类型转换
 */
inline fun <reified T> Any?.cast(block: T.() -> Unit) {
    if (this != null && this is T) {
        block(this.also(block))
    }
}

inline fun tryCatch(block: () -> Unit) {
    try {
        block()
    } catch (e: Exception) {
       e.printStackTrace()
    }
}